<?php

namespace App\Http\Controllers\Admin;

use Illuminate\Http\Request;
use App\Http\Controllers\Controller;
use DB;
use Session;
use Route;

use App\Http\Common\NodeService;
use App\Http\Common\LogService;

class LoginController extends Controller
{
    
    /**
     * 用户登录
     * @return string
     */
    public function index(Request $req) {

        if ($req->isMethod('get')) {
            $title = '用户登录';
            return view('admin.login',compact('title'));
        } else {
            $username = $req->username;
            $password = $req->password;

            if(empty($username) || strlen($username) < 4){
                return response()->json(['code' => 0, 'data' => '', 'msg' => '登录账号长度不能少于4位有效字符!', 'url' => '', 'wait' => 3]);
            } else if (empty($password) || strlen($password) < 4){
                return response()->json(['code' => 0, 'data' => '', 'msg' => '登录密码长度不能少于4位有效字符!', 'url' => '', 'wait' => 3]);
            }

            $user = DB::table('system_user')->where('username', $username)->first();
            if(empty($user)){
                return response()->json(['code' => 0, 'data' => '', 'msg' => '登录账号不存在，请重新输入!', 'url' => '', 'wait' => 3]);
            }
            if($user->password !== md5($password)){
                return response()->json(['code' => 0, 'data' => '', 'msg' => '登录密码与账号不匹配，请重新输入!', 'url' => '', 'wait' => 3]);
            }

            DB::table('system_user')->where('username', $user->username)->update(['login_at' => date('Y-m-d H:i:s')]);
            DB::table('system_user')->where('username', $user->username)->increment('login_num');
            Session::put('user', $user);
            // !empty($user->authorize) && NodeService::applyAuthNode();
            LogService::write($req, '系统管理', '用户登录系统成功');

            return response()->json(['code' => 1, 'data' => '', 'msg' => '登录成功，正在进入系统...', 'url' => 'admin/index', 'wait' => 3]);
        }
    }

    /**
     * 退出登录
     */
    public function out(Request $req) {
        LogService::write($req, '系统管理', '用户退出系统成功');
        Session::flush();
        return response()->json(['code' => 1, 'data' => '', 'msg' => '退出登录成功！', 'url' => '/', 'wait' => 3]);
    }
}
